package com.tanhua.geteway.filters;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@RefreshScope
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${gateway.excludedUrls}")
    private List<String> excludedUrls; // 白名单配置

    /**
     * 统一鉴权
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 白名单放行, 发送验证码与登录校验
        String requestPath = request.getURI().getPath();
        log.info("请求了地址: " + requestPath);
        // 白名单中包含这个路径则放行
        if (excludedUrls.contains(requestPath)) {
            return chain.filter(exchange);
        }

        //1. 获取token
        String token = request.getHeaders().getFirst("Authorization");
        //1.1 有值处理
        if(StringUtils.isNotEmpty(token)) {
            token = token.replace("Bearer ","");
            // 【注意】从登录成功的代码中，token存入redis的使用的key
            String tokenKey = "TOKEN_" + token;
            // 通过tokenkey获取登录用户的信息 jsonString
            String userJsonString = stringRedisTemplate.opsForValue().get(tokenKey);
            // 有值
            if(StringUtils.isNotEmpty(userJsonString)){
                // 放行
                return chain.filter(exchange);
            }
        }
        log.error("用户未登录");
        //没值 401， 用户没有登录
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 响应头中说明，返回的数据是json
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        // 具体响应给前端的数据
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("errCode", HttpStatus.UNAUTHORIZED.value());
        responseData.put("errMessage", "用户未登录");
        // 响应式编程
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(responseData));
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
